﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls.Expressions;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;
using Common.BaseLibrary.Authorization;

namespace DepartmentWork.Platform.Areas.SystemSettingArea.Controllers
{
    public class RoleController : BaseController
    {
        /// <summary>
        /// 权限列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string flag = "", string flagInfo = "")
        {
            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;

            #region 校验用户是否登录

            if (CurrentUser.UserID == "")
            {
                return RedirectToAction("Login", "Home",
                    new { area = "", returnUrl = Request.Url.ToString() });
            }

            #endregion

            #region 校验身份

            ViewBag.IsAdmin = false;
            string[] pathArr = Request.Path.Split('/');
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
            for (int i = 0; i < menuRole.Count(); i++)
            {
                int menuId = menuRole[i].MENU_ID;
                MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
                if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                {
                    ViewBag.IsAdmin = true;
                    break;
                }
            }


            #endregion

            List<MenuViewModel> menuModel = new List<MenuViewModel>();

            List<MENU> menuList = menuRepository.GetModel(r => r.ACTION_NAME!="").ToList();
            menuModel.AddRange((from item in menuList
                                select new MenuViewModel()
                                {
                                    ACTION_NAME = item.ACTION_NAME,
                                    AREA_NAME = item.AREA_NAME,
                                    BOOT_MENU_ID = item.BOOT_MENU_ID,
                                    CONTROLLER_NAME = item.CONTROLLER_NAME,
                                    MENU_CONTEXT = item.MENU_CONTEXT,
                                    MENU_ID = item.MENU_ID,
                                    MENU_NAME = item.MENU_NAME,
                                    MENU_STATUS = item.MENU_STATUS,
                                    MENU_CLASS = item.MENU_CLASS
                                }).ToList());

            for (int i = 0; i < menuModel.Count(); i++)
            {
                int id = menuModel[i].MENU_ID;
                menuModel[i].CHILDEN_COUNT = menuModel.FindAll(r => r.BOOT_MENU_ID == id).Count();
            }

            TempData["MenuList"] = menuModel;


            TeamSpaceRoleViewModel model = new TeamSpaceRoleViewModel();
            model.roleList = new List<RoleViewModel>();
            model.teamSpaceList = new List<TeamSpaceViewModel>();
            Guid userTeamspaceId = userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID)).FirstOrDefault().TEAMSPACE_ID;
            List<TEAMSPACE> teamspacesList = teamspaceRepository.GetModel(r => r.TEAMSPACE_ID == userTeamspaceId).ToList();
            List<ROLE_INFO> roleList = roleRepository.GetModel(r => r.TEAMSPACE_ID == userTeamspaceId).ToList();

            model.teamSpaceList.AddRange((from item in teamspacesList
                                          select new TeamSpaceViewModel()
                                          {
                                              TEAMSPACE_ID = item.TEAMSPACE_ID,
                                              TEAMSPACE_NAME = item.TEAMSPACE_NAME
                                          }).ToList());

            model.roleList.AddRange((from item in roleList
                                     select new RoleViewModel()
                                     {
                                         DESCRIPTION = item.DESCRIPTION,
                                         ROLE_ID = item.ROLE_ID,
                                         ROLE_NAME = item.ROLE_NAME,
                                         STATUE = item.STATUE,
                                         TEAMSPACE_ID = item.TEAMSPACE_ID
                                     }).ToList());

            return View(model);
        }

        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateRole(FormCollection collection)
        {
            ROLE_INFO role = new ROLE_INFO();
            role.ROLE_ID = roleRepository.GetModel().Count() + 1;
            role.ROLE_NAME = collection["tb_RoleName"];
            role.DESCRIPTION = collection["tb_CreateRoleContext"];
            if (collection["ck_CreateStatus"] == "on")
            {
                role.STATUE = 0;
            }
            else
            {
                role.STATUE = 1;
            }
            Guid teamId = userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID))
                .FirstOrDefault()
                .TEAMSPACE_ID;
            role.TEAMSPACE_ID = teamId;

            string[] menuSelectArr = collection["ck_CreateRoleMenu"].Split(',');

            //List<MENU_ROLE> menuRoleList = new List<MENU_ROLE>();

            int menuRoleCount = menuRoleRepository.GetModel().Count();

            try
            {
                roleRepository.Insert(role);
                Guid teamGuid =
                    teamspaceRepository.GetModel(r => r.TEAMSPACE_NAME == CurrentUser.Department)
                        .FirstOrDefault()
                        .TEAMSPACE_ID;
                int id = roleRepository.GetModel
                    (r => r.ROLE_NAME == role.ROLE_NAME && r.TEAMSPACE_ID == teamGuid).FirstOrDefault()
                    .ROLE_ID;
                for (int i = 0; i < menuSelectArr.Length; i++)
                {
                    MENU_ROLE menuRole = new MENU_ROLE();
                    menuRole.MENU_ID = Convert.ToInt32(menuSelectArr[i]);
                    menuRole.ROLE_ID = id;
                    menuRole.MENU_ROLE_ID = menuRoleCount + 1;
                    menuRoleCount += 1;
                    //menuRoleList.Add(menuRole);
                    menuRoleRepository.Insert(menuRole);
                }
                return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "CreateTrue" });
            }
            catch (Exception ex)
            {
                return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "CreateFalse", flagInfo = ex.Message });
            }
        }

        /// <summary>
        /// 获取该权限详细信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult GetRoleInfo(int roleId)
        {
            RoleViewModel model = new RoleViewModel();

            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == roleId).FirstOrDefault();

            model.ROLE_ID = role.ROLE_ID;
            model.ROLE_NAME = role.ROLE_NAME;
            model.STATUE = role.STATUE;
            model.DESCRIPTION = role.DESCRIPTION;

            List<MENU_ROLE> menuRoleList = menuRoleRepository.GetModel(r => r.ROLE_ID == roleId).ToList();

            //List<MENU> menuList=new List<MENU>();

            model.MenuList = new List<MenuViewModel>();

            try
            {
                for (int i = 0; i < menuRoleList.Count(); i++)
                {
                    //MENU menu=new MENU();
                    int id = menuRoleList[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == id).FirstOrDefault();
                    MenuViewModel item = new MenuViewModel();
                    item.MENU_NAME = menu.MENU_NAME;
                    item.MENU_ID = menu.MENU_ID;
                    item.BOOT_MENU_ID = menu.BOOT_MENU_ID;
                    model.MenuList.Add(item);
                }

            }
            catch (Exception)
            {
                throw;
            }

            return Json(model);
        }

        /// <summary>
        /// 编辑权限
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditRole(FormCollection collection)
        {
            #region 获取表单数据

            int roleId = Convert.ToInt32(collection["hid_EditRoleId"]);

            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == roleId).FirstOrDefault();

            role.ROLE_NAME = collection["tb_EditRoleName"].Trim() == "" ? role.ROLE_NAME : collection["tb_EditRoleName"];

            role.DESCRIPTION = collection["tb_EditRoleContext"].Trim() == "" ? role.DESCRIPTION : collection["tb_EditRoleContext"];

            if (collection["ck_EditStatus"] == "on")
            {
                role.STATUE = 0;
            }
            else
            {
                role.STATUE = 1;
            }

            #endregion

            #region 若冻结权限，判断该权限下是否还存在正常（未禁用）的用户

            if (role.STATUE == 1)
            {
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.ROLE_ID == roleId).ToList();

                if (userTeams != null && userTeams.Count != 0)
                {
                    for (int i = 0; i < userTeams.Count; i++)
                    {
                        Guid userId = userTeams[i].USER_ID;
                        USER_INFO user = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault();
                        if (user.ENABLE == "0")
                        {
                            return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "EditTrue", flagInfo = "编辑失败，请先禁用隶属该权限的用户，再冻结该权限！" });
                        }
                    }
                }

            }

            #endregion

            try
            {
                #region 更新权限

                roleRepository.Update(role);

                #endregion

                #region 更新权限所对应的菜单

                List<MENU_ROLE> menuRolesList = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();

                if (menuRolesList != null && menuRolesList.Count == 0)
                {
                    for (int i = 0; i < menuRolesList.Count(); i++)
                    {
                        menuRoleRepository.Delete(menuRolesList[i]);
                    }
                }

                string[] menuSelectArr = collection["ck_EditRoleMenu"].Split(',');

                int menuRoleCount = menuRoleRepository.GetModel().Count();

                for (int i = 0; i < menuSelectArr.Length; i++)
                {
                    MENU_ROLE menuRole = new MENU_ROLE();
                    menuRole.MENU_ID = Convert.ToInt32(menuSelectArr[i]);
                    menuRole.ROLE_ID = roleId;
                    menuRole.MENU_ROLE_ID = menuRoleCount + 1;
                    menuRoleCount += 1;
                    //menuRoleList.Add(menuRole);
                    menuRoleRepository.Insert(menuRole);
                }

                #endregion

                return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "EditTrue" });

            }
            catch (Exception ex)
            {
                return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "EditTrue", flagInfo = ex.Message });
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ActionResult DelRole(int roleId)
        {
            int userCount = userTeamsapceRepository.GetModel(r => r.ROLE_ID == roleId).Count();

            //若该权限下还存在人员，则无法删除权限！
            if (userCount != 0)
            {
                return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "DelFalse", flagInfo = "请先删除该权限下的全部人员，再删除该权限！" });
            }
            else
            {
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == roleId).FirstOrDefault();
                try
                {
                    roleRepository.Delete(role);
                    List<MENU_ROLE> menuRolesList = menuRoleRepository.GetModel(r => r.ROLE_ID == roleId).ToList();
                    if (menuRolesList != null && menuRolesList.Count == 0)
                    {
                        for (int i = 0; i < menuRolesList.Count; i++)
                        {
                            menuRoleRepository.Delete(menuRolesList[i]);
                        }
                    }
                    return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "DelTrue" });
                }
                catch (Exception ex)
                {
                    return this.RedirectToAction("Index", "Role", new { area = "SystemSettingArea", flag = "DelFalse", flagInfo = ex.Message });
                }

            }
        }
    }
}